const path = require('path');
const fs = require('fs');
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

// const splitChunks = {
//   chunkIds: "named",
//   runtimeChunk: 'single',
//   splitChunks: {
//     chunks: 'all',
//     cacheGroups: {
//       vendors: {
//         name: 'chunk-vendors',
//         test: /[\\/]node_modules[\\/]/,
//         priority: 10,
//         reuseExistingChunk: true,
//       },
//       react: {
//         name: 'chunk-react',
//         test: /[\\/]node_modules[\\/]react(.*)/,
//         priority: 20,
//         reuseExistingChunk: true,
//       }
//     }
//   }
// }

/* 直接导出函数
module.exports = function override(config, env) { 
  config.output.clean = true;
  // config.output.path = resolveApp('dist');
  config.output.filename = 'static/js/[name].[contenthash:6].chunk.js';
  
  config.optimization.minimizer[0].options.extractComments = false;
  config.optimization.minimizer[0].options.terserOptions = {
    compress: {
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log']
    },
    format: {
      comments: false
    }
  }

  config.optimization = {
    ...config.optimization,
    ...splitChunks
  }

  console.log(config);
  console.log(env);
  return config;
}
*/

// 通过导出对象的方式
/*
module.exports = {
  webpack: function(config, env) {
    config.output.clean = true;
    // config.output.path = resolveApp('dist');
    config.output.filename = 'static/js/[name].[contenthash:6].chunk.js';
    
    config.optimization.minimizer[0].options.extractComments = false;
    config.optimization.minimizer[0].options.terserOptions = {
      compress: {
        drop_console: true,
        drop_debugger: true,
        pure_funcs: ['console.log']
      },
      format: {
        comments: false
      }
    }

    config.optimization = {
      ...config.optimization,
      ...splitChunks
    }
    return config;
  },
  jest: function(config) {
    return config;
  },
  devServer: function(configFunction) {
  },
  paths: function(paths, env) {
    paths.appBuild = resolveApp('dist');
    return paths;
  },
}
*/

// ====== customize-cra ======
const {
  override,
  addWebpackAlias,
  tap,
  addWebpackPlugin,
  setWebpackOptimizationSplitChunks,
  overrideDevServer,
  watchAll,
  adjustStyleLoaders
} = require('customize-cra');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionPlugin = require("compression-webpack-plugin");
const isProduction = process.env.NODE_ENV === 'production';

/*
module.exports = override(
  (config, env) => { 
    config.output.clean = true;
    config.output.filename = 'static/js/[name].[contenthash:6].chunk.js';
    return config;
  },
  addWebpackAlias({
    "@": resolveApp("src"),
    "@assets": resolveApp("src/assets"),
    "@components": resolveApp("src/components"),
  }),
  isProduction && addWebpackPlugin(
    new BundleAnalyzerPlugin()
  ),
  tap({message: 'customize-cra'})
)
*/

const customizeConfig = () => (config,env) => { 

  if (env === 'production') { 
    config.devtool = false;
    config.output.clean = true;
    config.optimization.minimizer[0].options.extractComments = false;
    config.optimization.runtimeChunk = 'single';
    config.plugins.push(
      new CompressionPlugin({
        test: /\.(js|css)(\?.*)?$/,
        threshold: 1024,
        algorithm: 'gzip',
      })
    );
  }

  return config
}

// 开发阶段跨域配置（推荐还是直接在src目录下创建setupProxy.js文件）
const devServerConfig = () => (configFunction) => { 
  return {
    ...configFunction,
    compress: true,
    proxy: {
      "/api": {
        target: 'http://localhost:5000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

module.exports = {
  webpack: override(
    customizeConfig(),
    addWebpackAlias({
      "@": resolveApp("src"),
      "@assets": resolveApp("src/assets"),
      "@components": resolveApp("src/components"),
    }),
    isProduction && addWebpackPlugin(
      new BundleAnalyzerPlugin()
    ),
    isProduction && setWebpackOptimizationSplitChunks({
      chunks: 'all',
      cacheGroups: {
        vendors: {
          name: 'chunk-vendors',
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          reuseExistingChunk: true,
        },
        react: {
          name: 'chunk-react',
          test: /[\\/]node_modules[\\/]react(.*)/,
          priority: 20,
          reuseExistingChunk: true,
        }
      }
    }),
    adjustStyleLoaders(rule => { 
      if(rule.test.toString().includes('scss')) { 
        rule.use.push({
          loader: 'sass-resources-loader',
          options: {
            resources: [
              resolveApp('src/assets/styles/variables.scss'),
            ]
          }
        })
      }
    })
  ),
  jest: function(config) {
    return config;
  },
  devServer: overrideDevServer(
    devServerConfig(),
    watchAll()
  ),
  paths: function(paths, env) {
    return paths;
  },
}
